package com.xzt.bookstore.controller;

import com.xzt.bookstore.common.Result;
import com.xzt.bookstore.dto.LoginRequest;
import com.xzt.bookstore.dto.LoginResponse;
import com.xzt.bookstore.dto.RegisterRequest;
import com.xzt.bookstore.entity.User;
import com.xzt.bookstore.service.UserService;
import com.xzt.bookstore.util.JwtUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final UserService userService;
    private final JwtUtil jwtUtil;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@Valid @RequestBody RegisterRequest request) {
        try {
            User user = userService.register(
                    request.getUsername(),
                    request.getPassword(),
                    request.getEmail(),
                    request.getPhone(),
                    request.getNickname()
            );
            return Result.success("注册成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        // 查找用户
        User user = userService.findByUsername(request.getUsername());
        if (user == null) {
            return Result.error(401, "用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() == 0) {
            return Result.error(403, "用户已被禁用");
        }
        
        // 验证密码
        if (!userService.validatePassword(request.getPassword(), user.getPassword())) {
            return Result.error(401, "用户名或密码错误");
        }
        
        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getUsername(), user.getId());
        
        // 构建响应
        LoginResponse response = LoginResponse.builder()
                .token(token)
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .build();
        
        return Result.success("登录成功", response);
    }
}

